package x.ovo.wechat.bot.plugin.push;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

import org.dromara.hutool.core.text.StrUtil;

@Slf4j(topic = "PushPlusPushStrategy")
public class PushPlusPushStrategy implements PushStrategy {

    private static final String URL = "https://www.pushplus.plus/send";

    @Override
    public void push(Map<String, ?> config, OkHttpClient client, String flag, String content) {
        String accessToken = (String) config.get("access_token_pushplus");
        if (StrUtil.isBlank(accessToken)) log.info("PushPlus推送：配置文件未配置“access_token_pushplus”");
        else {
            JSONObject json = JSONUtil.ofObj()
                    .set("token", accessToken)
                    .set("title", "wechatbot通知")
                    .set("content", flag + ": " + content);
            Request request = new Request.Builder()
                    .url(URL)
                    .post(RequestBody.create(json.toString(), MediaType.parse("application/json")))
                    .build();
            try (Response response = client.newCall(request).execute()) {
                JSONObject object = JSONUtil.parseObj(response.body().string());
                if (object.getInt("code") == 200 && object.getStr("msg").equals("请求成功")) {
                    log.info("PushPlus推送成功");
                } else {
                    log.error("PushPlus推送失败");
                }
            } catch (IOException e) {
                log.error("PushPlus推送失败: {}", e.getMessage());
            }
        }
    }
}
